

import java.awt.AWTException;
import java.awt.AlphaComposite;
import java.awt.Composite;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;

import javax.swing.JComponent;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class AnimatingComp extends JPanel{
	private Dimension animatingSize = new Dimension(0, 1);
	JComponent source;
	BufferedImage offscreenImage;
	BufferedImage offscreenBackImage;
	private float percent = 0;
	private Dimension totalSize;
	
	public AnimatingComp(){
		super();
		setOpaque(true);
	}
	
	public void setSource(JComponent source, Rectangle screenRect){
		this.source = source;
		totalSize= source.getSize();
		makeOffscreenImage(source, screenRect);
	}
	
	private void makeOffscreenImage(JComponent source, Rectangle screenRect){
		GraphicsConfiguration gfxConfig = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
	    offscreenImage = gfxConfig.createCompatibleImage(source.getWidth(), source.getHeight());
	    
	    Graphics2D offscreenGraphics = (Graphics2D)offscreenImage.getGraphics();
	    source.paint(offscreenGraphics);
	    
	    //截屏
	    Robot robot;
		try {
			robot = new Robot();
			offscreenBackImage = robot.createScreenCapture(screenRect);
		} catch (AWTException e) {e.printStackTrace();}
	 //   Rectangle rect = new Rectangle(startLocation.x, startLocation.y, animatingSize.width, animatingSize.height);
	   // Dimension screen_size = Toolkit.getDefaultToolkit().getScreenSize();
		//Rectangle screen_rect = new Rectangle(0,0, screen_size.width, screen_size.height);
	}
	
	public void setPercent(float p){
		percent = p;
		animatingSize.height = totalSize.height;
		animatingSize.width = (int) (totalSize.width * p);
		this.setSize(animatingSize);
	}
	
	public Dimension getPreferredSize(){
		return animatingSize;
	}
	
	public Dimension getMinimumSize(){
		return animatingSize;
	}
	public Dimension getMaximumSize(){
		return animatingSize;
	}
	
	public void update(Graphics g){
		paint(g);
	}
	
	public void paint(Graphics g){
		try{
			if(offscreenBackImage != null){
				g.drawImage(offscreenBackImage, 0, 0, this);//
			}
		//System.out.println("fafaf");
		BufferedImage fragment = this.offscreenImage.getSubimage(totalSize.width - animatingSize.width,0,// offscreenImage.getHeight() - animatingSize.height,
				 animatingSize.width, animatingSize.height);
       
		Composite fade = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 
				percent);

		((Graphics2D) g).setComposite(fade);
		
		g.drawImage(fragment, 0, 0, this);
		}catch(Exception e){
			e.printStackTrace();
			//System.out.println(offscreenImage.getWidth() + " " + offscreenImage.getHeight());
			//System.out.println(animatingSize.width + " " + animatingSize.height);
		}
	}

}
